package com.quanthium.monitor.rocketmq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@RocketMQMessageListener(topic = "${rocketmq.consumer.alarm.topic}", consumerGroup = "${rocketmq.consumer.group}")
public class AlarmErrorConsumer implements RocketMQListener<String> {
    @Value("${spring.boot.admin.notify.dingtalk.webhook-url}")
    private String WEBHOOK_URL;
    @Value("${spring.boot.admin.notify.dingtalk.secret}")
    private String SECRET;
    private static final RestTemplate restTemplate = new RestTemplate();
    @Override
    public void onMessage(String s) {
        try {
            long timestamp = System.currentTimeMillis();
            String stringToSign = timestamp + "\n" + SECRET;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
            String sign = URLEncoder.encode(Base64.getEncoder().encodeToString(signData), StandardCharsets.UTF_8.toString());

            String urlWithSignature = WEBHOOK_URL + "&timestamp=" + timestamp + "&sign=" + sign;
            Map<String, Object> messageJson = new HashMap<>();
            messageJson.put("msgtype", "text");

            Map<String, Object> content = new HashMap<>();
            content.put("content", s);
            messageJson.put("text", content);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(messageJson, headers);
            restTemplate.postForObject(urlWithSignature, request, String.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
